package socket;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Client {
    private Socket socket;

    public Client() {
        try {
            System.out.println("正在连接客服端...");
            socket = new Socket("176.55.10.15", 8088);
            System.out.println("服务器连接成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start() {
        try {
            OutputStream out = socket.getOutputStream();
            OutputStreamWriter psw = new OutputStreamWriter(out, StandardCharsets.UTF_8);
            BufferedWriter bw = new BufferedWriter(psw);
            PrintWriter pw = new PrintWriter(bw, true);
            Scanner scan = new Scanner(System.in);

            while (true) {
                System.out.println("请输入昵称");
                String nickname = scan.nextLine();
                if (nickname.trim().isEmpty()&&nickname.matches("^ +$")){
                    System.out.println("用户名不能为空");
                }else {
                    pw.println(nickname);
                    break;
                }
            }

            Thread t = new Thread(new ServerHandler());
            t.setDaemon(true);
            t.start();
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            while (true) {
                Thread.sleep(100);
                System.out.println("请输入内容(输入exit退出)：");
                String str = scan.nextLine();
                if ("exit".equalsIgnoreCase(str)) {
                    pw.println("已退出");
                    break;
                }
                pw.println(str);
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Client client = new Client();
        client.start();
    }

    private class ServerHandler implements Runnable{
        @Override
        public void run() {
            try {
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);

                while (true){
                    System.out.println(br.readLine());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
